package com.zhb.cloud.config;

import org.apache.curator.RetryPolicy;
import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.CuratorFrameworkFactory;
import org.apache.curator.framework.api.UnhandledErrorListener;
import org.apache.curator.framework.imps.CuratorFrameworkState;
import org.apache.curator.framework.state.ConnectionState;
import org.apache.curator.framework.state.ConnectionStateListener;
import org.apache.curator.retry.ExponentialBackoffRetry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@ConfigurationProperties(prefix = "zookeeper")
public class ZookeeperConfig {
	private static final Logger logger = LoggerFactory.getLogger(ZookeeperConfig.class);
	/**
	 * zk主机
	 */
	private String hosts;

	/**
	 * 命名空间--全局命名空间
	 */
	private String namespace;

	/**
	 * sessionTimeoutMs会话超时时间，单位为毫秒。默认是60000ms
	 */
	private int sessionTimeoutMs;
	/**
	 * connectionTimeoutMs连接创建超时时间，单位毫秒，默认15000ms
	 */
	private int connectionTimeoutMs;
	/**
	 * 间隔时间基数
	 */
	private int baseSleepTimeMs;
	/**
	 * 重连策略:最大重试次数
	 */
	private int maxRetries;

	/**
	 * @Description: CuratorFramework 初始化连接的客户端
	 * @return
	 */
	public @Bean CuratorFramework getCuratorFramework() {
		CuratorFramework client = CuratorFrameworkFactory.newClient(hosts, sessionTimeoutMs, connectionTimeoutMs,
				getRetryPolicy());
		client.getConnectionStateListenable().addListener(connectionStateListener());
		client.getUnhandledErrorListenable().addListener(unhandledErrorListener());
		client.usingNamespace(namespace);
		// 启动zk客户端
		if (client.getState() != CuratorFrameworkState.STARTED) {
			client.start();
		}
		return client;
	}

	/**
	 * @Description: 重连策略
	 * @return
	 */
	public @Bean RetryPolicy getRetryPolicy() {
		return new ExponentialBackoffRetry(baseSleepTimeMs, maxRetries);
	}

	/**
	 * @Description:连接状态监听
	 * @return
	 */
	public @Bean ConnectionStateListener connectionStateListener() {
		return new ConnectionStateListener() {
			@Override
			public void stateChanged(CuratorFramework client, ConnectionState newState) {
				logger.info("CuratorFramework client 客户端状态发生了改变");
				if (newState == ConnectionState.CONNECTED || newState == ConnectionState.RECONNECTED) {
					System.out.println("DSFDSA");
				}
			}
		};
	}

	/**
	 * @Description: 未处理的连接异常
	 * @return
	 */
	public @Bean UnhandledErrorListener unhandledErrorListener() {
		return new UnhandledErrorListener() {

			@Override
			public void unhandledError(String message, Throwable e) {
				logger.info("CuratorFramework unhandledError: {}", message);
			}
		};
	}

}
